<template>
	<div id="cesiumContainer"></div>
</template>

<script>
	import bus from '@/util/bus'
	var Cesium = require("cesium/Cesium");
	var widgets = require("cesium/Widgets/widgets.css");
	export default {
		name: "",
		data(){
			return {
				// 假数据的坐标(有经纬度就可以直接操作了 没有的话只能从图中转义)
				list:[
					{x: -2582836.259013077, y: 4664016.259406846, z: 3489155.7461206513},
					{x: -2583198.2266520527, y: 4664182.562123221, z: 3488668.655161815},
					{x: -2583193.1629041894, y: 4664007.867714716, z: 3488904.4949902766}
				]
			}
		},
		mounted() {
            let that=this
			var viewer = new Cesium.Viewer("cesiumContainer", {
				terrainProvider: Cesium.createWorldTerrain(),
				animation: false, // 左下角的动画仪表盘 
				baseLayerPicker: false, // 右上角的图层选择按钮
				navigationHelpButton: false, // 右上角的帮助按钮        
				sceneModePicker: false, // 右上角模式切换按钮
				homeButton: false, // 右上角home按钮
				geocoder: false, // 右上角搜索框
				timeline: false, // 底部的时间轴 
				sceneMode: 3,
				fullscreenButton: false, //右下角的全屏按钮         
				infoBox: false,
			});

			// ====== 只显示模型区域设置 ========
			//			viewer.scene.sun.show = false; //在Cesium1.6(不确定)之后的版本会显示太阳和月亮，不关闭会影响展示
			//			viewer.scene.moon.show = false;
			//			viewer.scene.skyBox.show = false; //关闭天空盒，否则会显示天空颜色
			//			viewer.scene.undergroundMode = true; //重要，开启地下模式，设置基色透明，这样就看不见黑色地球了
			//			viewer.scene.globe.show = false; //不显示地球，这条和地球透明度选一个就可以
			//			viewer.scene.globe.baseColor = new Cesium.Color(0, 0, 0, 0);
			//			viewer.scene.backgroundcolor = new Cesium.Color(0, 0, 0, 0);

			// 创建聚焦函数 1
			function defined(value) {
				return value !== undefined && value !== null;
			}
			// 创建聚焦函数 2
			function selectEntity(value) {
				if(viewer._selectedEntity !== value) {

					viewer._selectedEntity = value;
					var selectionIndicatorViewModel = defined(viewer._selectionIndicator) ? viewer._selectionIndicator.viewModel : undefined;
					if(defined(value)) {
						if(defined(selectionIndicatorViewModel)) {
							selectionIndicatorViewModel.animateAppear();
						}
					} else if(defined(selectionIndicatorViewModel)) {
						selectionIndicatorViewModel.animateDepart();
					}
					viewer._selectedEntityChanged.raiseEvent(value);
				}
			}

			//设置中键放大缩小
			viewer.scene.screenSpaceCameraController.zoomEventTypes = [
				Cesium.CameraEventType.WHEEL,
				Cesium.CameraEventType.MIDDLE_DRAG,
				Cesium.CameraEventType.PINCH
			];
			//设置右键旋转
			viewer.scene.screenSpaceCameraController.tiltEventTypes = [
				Cesium.CameraEventType.RIGHT_DRAG,
				Cesium.CameraEventType.PINCH,
				{
					eventType: Cesium.CameraEventType.RIGHT_DRAG,
					modifier: Cesium.KeyboardEventModifier.CTRL
				},
				{
					eventType: Cesium.CameraEventType.MIDDLE_DRAG,
					modifier: Cesium.KeyboardEventModifier.CTRL
				}
			];
			var annotations = viewer.scene.primitives.add(new Cesium.LabelCollection());
			//  加载3Dtile倾斜摄影
			const tileset = new Cesium.Cesium3DTileset({
				url: '/cesium/photography/000000/json/tileset.json'
			});
			
			tileset.readyPromise.then(function(tileset) {
				// 模型贴地操作
	            var height = -50;  // 设置模型贴地高度 如果不设置的话会导致点位和连线被遮挡(因为无人机相机的高度是28米 导致模型的高度是28米)              
				var cartographic = Cesium.Cartographic.fromCartesian(tileset.boundingSphere.center);
				var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, cartographic.height);
				var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude,height);
				var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
				tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);			
				viewer.scene.primitives.add(tileset);
				viewer.zoomTo(tileset, new Cesium.HeadingPitchRange(0.5, -0.5, tileset.boundingSphere.radius * 1.5));

				
				for(var i=0;i<that.list.length;i++){
					let cartographic = Cesium.Cartographic.fromCartesian(that.list[i]);
					let lng = Cesium.Math.toDegrees(cartographic.longitude); // 经度
					let lat = Cesium.Math.toDegrees(cartographic.latitude); // 纬度
					that.list[i].lng=lng
					that.list[i].lat=lat
					let height = cartographic.height
					let ellipsoid = viewer.scene.globe.ellipsoid;
					let degrees = Cesium.Cartographic.fromDegrees(lng, lat, height); 
					let cartesian = ellipsoid.cartographicToCartesian(degrees);
					let imgUrl=i%2==0?"/img/bigScreen/013.png":"/img/bigScreen/014.png"
					createPoint(cartesian,imgUrl)
					if(i==0){
						let position = Cesium.Cartesian3.fromDegrees(lng, lat, height);
						let model = new Cesium.Entity({
							position: position
						})
						selectEntity(model);
					}
				}
				polyline(that.list)



			}).otherwise(function(error) {
				console.log(error);
			});

			// 初始化渲染标注
			var handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);

			var handler1 = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

			handler1.setInputAction(function(click) {
				var pick = viewer.scene.pick(click.position);
				//选中某模型   pick选中的对象
				if(pick && pick.id) {
					// 显示弹出层
                   bus.$emit('showDialog',pick);  
					
				}
			}, Cesium.ScreenSpaceEventType.LEFT_CLICK);



			handler.setInputAction(function(event) {
				
				if(!Cesium.Entity.supportsPolylinesOnTerrain(viewer.scene)) {
					console.log('当前浏览器不支持地形图');
					return;
				}
				var earthPosition = viewer.scene.pickPosition(event.position); //获取到地形图上面的坐标
				console.log(earthPosition)
				if(Cesium.defined(earthPosition)) {
					createPoint(earthPosition); //调用创建点的方法
				}
			}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

			// 创建自定义窗口
			function annotate(cartesian, lng, lat, height) {
				createPoint(cartesian);
				annotations.add({
					position: cartesian,
					text: '纬度: ' + lng.toFixed(5) + '\u00B0' +
						'\经度: ' + lat.toFixed(5) + '\u00B0' +
						"\高度: " + height.toFixed(2) + "m",
					showBackground: true,
					font: '14px monospace',
					horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
					verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
					disableDepthTestDistance: Number.POSITIVE_INFINITY
				});
			}

			// 创建标记点   
			function createPoint(earthPosition,imgUrl) {
				viewer.entities.add({
					position: earthPosition,
					name: '123', // 顶部标题
					description: `<tabel><tr><td>经度为:</td><td>1234567</td></tr><tr><td>经度为:</td><td>1234567</td></tr></tabel>`,
					billboard: {
						// 图像地址，URI或Canvas的属性
						image: imgUrl,
						// 设置颜色和透明度
						height: 60,
						width: 45,
						rotation: 0,
						color: Cesium.Color.WHITE.withAlpha(0.8),
						// 大小是否以米为单位
						sizeInMeters: false,
						// 遮挡问题
						disableDepthTestDistance: Number.POSITIVE_INFINITY,
						// 相对于坐标的垂直位置
						verticalOrigin: Cesium.VerticalOrigin.CENTER,
						// 相对于坐标的水平位置
						horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
						// 该属性指定标签在屏幕空间中距此标签原点的像素偏移量 大概是一半的宽度和一半的高度 
						pixelOffset: new Cesium.Cartesian2(0, -30),
						// 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
						scale: 1,
						// 是否显示
						show: true,
					}
				});
			}
			
			
			function polyline(arr){
				let newArr=[]
				arr.forEach(item=>{
					newArr.push(item.lng)
					newArr.push(item.lat)
				})				
		        viewer.entities.add({
		            name : 'Red line on the surface',
		            polyline : {
		                positions : Cesium.Cartesian3.fromDegreesArray(newArr),
		                width : 2,
		                material : Cesium.Color.RED		               
		            }
		        }); 				
			}
			

	        
	        
			// 去掉底部版权信息  
			viewer.scene.globe.depthTestAgainstTerrain = false;
			viewer.cesiumWidget.creditContainer.style.display = "none";
		},
	};
</script>

<style scoped>
	* {
		box-sizing: border-box;
	}
	
	#cesiumContainer {
		position: absolute;
		z-index: 1;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
	}
</style>